import os
import sys
import time
import commands
import pexpect
import threading  as td
from threadpool import Worker,ThreadPool
class Run(object):
    """docstring for Run"""
    def __init__(self,no):
        self.no = no
        self.pool = ThreadPool(self.no)

    def start(self):     
        for v in self.procdata.input.keys():
            self.pool.add_task(d.task,v,self.procdata.output)



class Controller(object):
    """docstring for Controller"""
    def __init__(self,key):
        self.key=key
        self.user ="wisconsin_cloudmeasure"
        self.password="123456"
        self.conn_timeout=80
        self.trans_timeout=900
        self.setup_err="command not found"
        self.ok_host=[]
        self.err_host_timeout=[]
        self.err_host_slow=[]
        self.err_host_unexpected=[]
	self.useful=[]


    def test(self):
        t=Run(20)
        r=open("node_ok").readlines()
        #r=open("node_c1.txt").readlines()
        #r=list(set(r2)-set(r1))
        print len(r)
        c=0
        #st=1600000
        #ed=1880000
        #inter=(ed-st)/100
        #tt=[v.strip("\n") for v in open("left").readlines()]
        for l in r:
            #l=l.strip("\n")[:-3]
	    l=l.strip("\n")
	    if l[0]=="#":
		continue

            no=["0"+str(c%100) if c%100<10 else str(c%100)][0]
            
	    #sno=st+c*inter
            #eno=st+(c+1)*inter
            #cmd="python bl.py IPD_"+str(no)+" 20"
	    #cmd="python domain.py IP_"+str(no)+" 20"
	    cmd="cd UWM/ ;sudo python get_pic_m.py ../TA_"+str(no)+" 5"
	    #print cmd
            c=c+1
	    #print no
	    #continue
            #cmd="python check.py V4_"+str(no)
	    prex="IPS_"+str(no) 

	    cmd="cd UWM ;tar czf index.tar index;tar czf log.tar log;mv index.tar ../;mv log.tar ../"
	  
            t.pool.add_task(self.getback_single,"log.tar",l,l+".log.tar")

        t.pool.wait_completion()
        print self.err_host_timeout
        print self.err_host_unexpected
	print len(self.ok_host)




    def command_single(self,cmd,host):
        #print host
        command = 'ssh -o StrictHostKeyChecking=no  -t -i '+self.key+' '+self.user+'@' + host + " \'" + cmd  + "\'"
    	#command = 'ssh -o StrictHostKeyChecking=no  -t -i '+self.key+' '+self.user+'@' + host + " \'" + cmd +' 1>/dev/null  2>&1 &'  + "\'"
        #command = 'ssh -o StrictHostKeyChecking=no -t -i '+self.key+' '+self.user+'@' + host + " \'" + cmd  + ' 1>/dev/null ' "\'"
        #print command
	#return
	p=pexpect.spawn(command)
        p.setecho(True)
        #print command
        ssh_used_prompt='Enter passphrase for key \'' + self.key+ '\':'
        res=p.expect([ssh_used_prompt,pexpect.EOF,pexpect.TIMEOUT],timeout=self.conn_timeout)
        if res==0:
            #print "******Enter password******"
            #print command
            p.sendline(self.password)
            p.expect(pexpect.EOF,timeout=None )
            #print p.match
            #p.expect(pexpect.PROMPT)
            #self.ok_host.append(host)
            #print p.before
            t=p.before.strip().strip("\n\r\t")
            if t:
                print host,t
		self.ok_host.append(host)
                #try:
                #    if int(t)>10:
                #        self.useful.append(host+"\n")
                       
                #except:
                #    pass
               
            
            
        elif res==1:
            print "******Either got key or connection timeout******"
            self.err_host_unexpected.append(host)
            pass
        elif res==2:
            print "******Timeout******"
            self.err_host_timeout.append(host)
            pass

        pass

    def getback_single(self,src,host,dst):
        command ='scp -o StrictHostKeyChecking=no -i '+self.key+' '+self.user+'@' + host+':~/' + src + ' ./'+dst
        print command
        #return
        p=pexpect.spawn(command)
        p.setecho(True)
        #print command
        ssh_used_prompt='Enter passphrase for key \'' + self.key+ '\':'
        res=p.expect([ssh_used_prompt,pexpect.EOF,pexpect.TIMEOUT],timeout=self.conn_timeout)
        if res==0:
            #print "******Enter password******"
            #print command
            p.sendline(self.password)
            p.expect(pexpect.EOF,timeout=None )
            #print p.match
            #p.expect(pexpect.PROMPT)
            self.ok_host.append(host)
            #print p.before
            t=p.before.strip().strip("\n\r\t")
            if t:
                print host,t
            
            
        elif res==1:
            print "******Either got key or connection timeout******"
            self.err_host_unexpected.append(host)
            pass
        elif res==2:
            print "******Timeout******"
            self.err_host_timeout.append(host)
            pass

        pass

    def deploy_single(self,src,host,dst):
        command ='scp -o StrictHostKeyChecking=no -i '+self.key+' -r ./' + src +' '+self.user+'@' + host+':~/' + dst
        p=pexpect.spawn(command)
        ssh_new_prompt = 'Are you sure you want to continue connecting'
        ssh_used_prompt='Enter passphrase for key \'' + self.key+ '\':'
        res=p.expect([ssh_new_prompt,ssh_used_prompt,pexpect.EOF,pexpect.TIMEOUT],timeout=self.conn_timeout)
        print command
        if res==0:
            print "******Connecting******"
            p.sendline('yes')
            t=p.expect([ssh_new_prompt,ssh_used_prompt,pexpect.EOF,pexpect.TIMEOUT],timeout=self.conn_timeout)
            if t==0:
                print "******Enter Password******"
                p.sendline(self.password)
                try:
                    p.expect(pexpect.EOF,timeout=self.trans_timeout)
                    print p.before
                except:
                    self.err_host_slow.append(host)
                    print host,"Transfer Timeout"
                pass
            elif t==1:
                self.err_host_unexpected.append(host)
                print host,"Unexpected Errors"
                pass
            elif t==2:
                self.err_host_timeout.append(host)
                print host,"Connection Timeout"
                pass
            pass
        elif res==1:
            print "******Enter Password******"
            p.sendline(self.password)
            try:
                p.expect(pexpect.EOF,timeout=self.trans_timeout)
                print p.before
            except:
                self.err_host_slow.append(host)
                print host,"Transfer Timeout"
            pass

        elif res==2:
            self.err_host_unexpected.append(host)
            print host,"Unexpected Errors"
            pass
        elif res==3:#connection timeout
            self.err_host_timeout.append(host)
            print host,"Connection Timeout"
        p.expect(pexpect.EOF)
        pass


if __name__ == '__main__':
    #cmd=sys.argv[1]
    c=Controller("id_rsa_planetlab")
    c.test()
    #for l in open("node_200","r"):
     #   l=l.strip("\n")
     #   c.command_single(cmd, l)
   # test="planetlab1.ie.cuhk.edu.hk"
    #test1="dplanet2.uoc.edu"
    #c.deploy_single("test", test1, "big")
